<?php
/**
 * Created by PhpStorm.
 * User: wangjiangtao
 * Date: 2022/7/14
 * Time: 18:37
 */

namespace App\Modules\Popularize\Platform;


use App\Http\Model\AdvertiserCallbackLog;
use App\Http\Model\Device;
use App\Http\Model\Hint;
use App\Http\Model\MonitoringLink\AccessToken;
use App\Http\Model\MonitoringLink\HuaweiCallbackLogs;
use App\Http\Model\UserRegisterLog;
use App\Http\Services\AdvertiserCallbackLogServices;
use App\Http\Services\DeviceServices;

class PlatformGuangdiantong implements PlatformInterface {

    protected $callback;
    protected $platform;
    protected $device;
    protected $userId;

    const ACTIVITE_EVENT = 'ACTIVATE_APP';
    const REGISTER_EVENT = 'REGISTER';
    const PAY_EVENT = 'PURCHASE';

    /**
     * 来来
     */
    const TARGET_TYPE_LL = 1;
    /**
     * 广告商
     */
    const TARGET_TYPE_ADS = 2;
    /**
     * 记录状态
     */
    const STATE_RECORD = 1;

    /**
     * 回调成功
     */
    const STATE_SUCCESS = 2;

    /**
     * 回调失败
     */
    const STATE_FAIL = 3;


    public function __construct($callback,$platform, $device, $userId)
    {
        $this->callback = $callback;
        $this->platform = $platform;
        $this->device = $device;
        $this->userId = $userId;
    }

    public function active():?bool
    {
        $requestData = $this->_buildRequestData(self::ACTIVITE_EVENT);
        if (empty($requestData)) {
            return false;
        }
        $params = json_decode(json_encode($this->device),true);
        $params = $this->_checkField($params);
        try {
            if (isset($this->device->guid) && $this->device->guid != ''){
                //查询是否存在设备信息，如果存在就说明设备已经激活
                $deviceModel = new Device();
                $deviceInfo = $deviceModel->getByGuid($this->device->guid);
                if(!empty($deviceInfo)){
                    write_log('TencentAdvertiserService', 'platform_guangdiantong', ["设备已存在", $params]);
                    return false;
                }
                $deviceModel->save($params);

                //获取用户注册并修改渠道
                $model = new UserRegisterLog();
                $userRegisterLog = $model->findRecordByGuid($this->device->guid, ['user_id']);
                if ($userRegisterLog && $this->platform != '' && is_numeric($userRegisterLog['platform']) && $userRegisterLog['platform'] == $userRegisterLog['channel_id']) {
                    $model->updatePlatform($userRegisterLog['user_id'], $this->platform);
                }
                write_log('TencentAdvertiserService', 'platform_guangdiantong', ["保存设备信息成功", $params]);
                return $this->_report(self::ACTIVITE_EVENT, $requestData);
            }
            
        } catch (\Exception $e) {
            write_log('TencentAdvertiserService', 'platform_guangdiantong', ["保存设备信息失败", $params,$e->getMessage()]);
            return false;
        }
        return true;
    }

    public function regist():?bool
    {
        $requestData = $this->_buildRequestData(self::REGISTER_EVENT);
        if (empty($requestData)) {
            return false;
        }
        return $this->_report(self::REGISTER_EVENT, $requestData);
    }

    public function pay($amount = 0):?bool
    {
        $requestData = $this->_buildRequestData(self::PAY_EVENT, $amount);
        if (empty($requestData)) {
            return false;
        }
        return $this->_report(self::PAY_EVENT, $requestData);
    }

    /**
     * 获取设备信息
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|void|null
     */
    public function getDevice(){
        return $this->device;
    }

    private function _buildRequestData($type, $payAmount = 0){
        if ($payAmount > 0 && $payAmount < 6) {
            return [];
        }
        $requestData = [];
        $requestData['action_time'] = time();
        $requestData['action_type'] = $type;

        //ios
        if (isset($this->device->idfa) && !empty($this->device->idfa)){
            $requestData['user_id']['idfa'] = strtoupper($this->device->idfa);
            $requestData['user_id']['hash_idfa'] = md5($requestData['user_id']['idfa']);
        }
        //android
        if (isset($this->device->imei) && !empty($this->device->imei)){
            $requestData['user_id']['imei'] = strtolower($this->device->imei);
            $requestData['user_id']['hash_imei'] = md5($requestData['user_id']['imei']);
        }
        if (isset($this->device->oaid) && !empty($this->device->oaid)){
            $requestData['user_id']['oaid'] = $this->device->oaid;
            $requestData['user_id']['hash_oaid'] = md5($requestData['user_id']['oaid']);
        }

        if ($payAmount > 0) {
            $requestData['action_param']['value'] = $payAmount * 100;
        }
        return $requestData;
    }

    //上报广点通服务器
    private function _report($type, $requestData){
        if (empty($requestData)) {
            return false;
        }
        $requestData = [
            'actions'=>[$requestData]
        ];
        $insertId = (new AdvertiserCallbackLogServices())->insertData([
            'platform' => $this->platform??'',
            'device_md5_id' => (!empty($requestData['user_id']['hash_imei']) ? $requestData['user_id']['hash_imei'] : $requestData['user_id']['hash_idfa'])??'',
            'action_type' => $type,
            'target_type' => self::TARGET_TYPE_ADS,
            'state' => self::STATE_RECORD,
            'request_url' => $this->callback??'',
            'request_params' => json_encode($requestData),
        ]);
        $header = ['Content-Type' => 'application/json'];
        try{
            $result = curl_request($this->callback, $requestData, 'json', 'POST', $header);
            write_log('TencentAdvertiserService', 'platform_guangdiantong', [$this->callback, $requestData]);
            $dbStatus = (new AdvertiserCallbackLogServices())->updateByCondition(
                ['id' => $insertId],
                ['response_params' => json_encode($result),'state' => AdvertiserCallbackLog::STATE_SUCCESS]
            );
        }catch (\Exception $exception){
            $dbStatus = (new AdvertiserCallbackLogServices())->updateByCondition(['id' => $insertId], ['state' => AdvertiserCallbackLog::STATE_FAIL]);
            write_log('TencentAdvertiserService', 'platform_guangdiantong', [$this->callback, $requestData, 'error_msg'=> $exception->getMessage(), 'db_status' => $dbStatus]);
            return false;
        }
        $result = json_decode($result);

        return isset($result->code) &&  $result->code == 0;
    }

    protected function _checkField($params = [])
    {
        do {
            $checkField = ['cid', 'aid', 'callback','advertiser_id', 'guid', 'idfa', 'version_no', 'os_name', 'device', 'channel_id', 'platform','imei','oaid','adid','conv_ext', 'client_ip'];
            if (empty($params)) {
                break;
            }

            $inputParams = [];
            foreach ($checkField as $field) {
                if (array_key_exists($field, $params)) {
                    $inputParams[$field] = $params[$field];
                }
            }

            $params = $inputParams;
        } while (false);

        return $params;
    }
}
